<template>
  <div class="employee-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>员工管理</span>
          <div class="header-operations">
            <el-input
              v-model="searchQuery"
              placeholder="搜索员工姓名"
              style="width: 200px; margin-right: 10px"
            />
            <el-select v-model="roleFilter" placeholder="角色筛选" style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="前台人员" value="1" />
              <el-option label="技术人员" value="2" />
            </el-select>
            <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="在职" :value="1" />
              <el-option label="离职" :value="0" />
            </el-select>
            <el-button type="primary" @click="handleAdd">添加员工</el-button>
          </div>
        </div>
      </template>

      <el-table :data="employeeList" style="width: 100%">
        <el-table-column prop="id" label="员工ID" width="100" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.role)">
              {{ getRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加员工' : '编辑员工'"
      width="500px"
    >
      <el-form :model="employeeForm" label-width="100px" :rules="rules" ref="employeeFormRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="employeeForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="employeeForm.role" placeholder="请选择角色">
            <el-option label="前台人员" value="1" />
            <el-option label="技术人员" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="employeeForm.status" placeholder="请选择状态">
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const employeeList = ref([])
const searchQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const employeeFormRef = ref(null)
const employeeForm = reactive({
  id: null,
  name: '',
  phone: '',
  role: '',
  status: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取员工列表
const fetchEmployeeList = async () => {
  try {
    const token = localStorage.getItem('Token')
    const url = new URL('http://localhost:8080/employee/list')
    
    // 添加分页参数
    url.searchParams.append('page', currentPage.value)
    url.searchParams.append('size', pageSize.value)
    
    // 添加搜索参数
    if (searchQuery.value) {
      url.searchParams.append('name', searchQuery.value)
    }
    
    // 添加角色筛选参数
    if (roleFilter.value) {
      url.searchParams.append('role', roleFilter.value)
    }

    // 添加状态筛选参数
    if (statusFilter.value !== '') {
      url.searchParams.append('status', statusFilter.value)
    }

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    if (result.code === 200) {
      employeeList.value = result.data.records || []
      total.value = result.data.total || 0
      currentPage.value = result.data.current || 1
      pageSize.value = result.data.size || 10
    } else {
      throw new Error(result.message || '获取员工列表失败')
    }
  } catch (error) {
    console.error('获取员工列表失败：', error)
    ElMessage.error('获取员工列表失败：' + error.message)
  }
}

// 监听搜索和筛选条件变化
watch([searchQuery, roleFilter, statusFilter], () => {
  currentPage.value = 1 // 重置页码
  fetchEmployeeList()
})

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEmployeeList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchEmployeeList()
}

// 获取角色类型
const getRoleType = (role) => {
  const roleTypeMap = {
    '1': 'primary',    // 前台人员
    '2': 'warning'     // 技术人员
  }
  return roleTypeMap[role] || 'info'
}

// 获取角色文本
const getRoleText = (role) => {
  const roleTextMap = {
    '1': '前台人员',
    '2': '技术人员'
  }
  return roleTextMap[role] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  return status === 1 ? 'success' : 'danger'
}

// 获取状态文本
const getStatusText = (status) => {
  return status === 1 ? '在职' : '离职'
}

// 处理添加员工
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(employeeForm, {
    id: null,
    name: '',
    phone: '',
    role: '',
    status: ''
  })
  dialogVisible.value = true
}

// 处理编辑员工
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(employeeForm, {
    ...row,
    status: Number(row.status)
  })
  dialogVisible.value = true
}

// 处理删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该员工吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const token = localStorage.getItem('Token')
      const response = await fetch(`http://localhost:8080/employee/delete/${row.id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Token': token
        }
      })

      if (response.status === 401) {
        localStorage.removeItem('Token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('删除成功')
        fetchEmployeeList()
      } else {
        throw new Error(result.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败：', error)
      ElMessage.error('删除失败：' + error.message)
    }
  })
}

// 处理提交表单
const handleSubmit = async () => {
  if (!employeeFormRef.value) return
  
  await employeeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const token = localStorage.getItem('Token')
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8080/employee/add'
          : 'http://localhost:8080/employee/update'
        
        // 确保status是数字类型
        const formData = {
          ...employeeForm,
          status: Number(employeeForm.status)
        }
        
        const response = await fetch(url, {
          method: dialogType.value === 'add' ? 'POST' : 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Token': token
          },
          body: JSON.stringify(formData)
        })

        if (response.status === 401) {
          localStorage.removeItem('Token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          return
        }

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchEmployeeList()
        } else {
          throw new Error(result.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败：', error)
        ElMessage.error('操作失败：' + error.message)
      }
    }
  })
}

// 在组件挂载时获取员工列表
onMounted(() => {
  fetchEmployeeList()
})
</script>

<style scoped>
.employee-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 